package com.zhanglinwei.openApiServer.context;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.zhanglinwei.openApiClient.constants.OpenApiConstant.*;

public class OpenApiRequestContext {

    private static final ThreadLocal<Map<String, String>> CONTEXT = ThreadLocal.withInitial(HashMap::new);

    public static void put(String key, String value) {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
            return;
        }
        CONTEXT.get().put(key, value);
    }

    public static String get(String key) {
        return CONTEXT.get().get(key);
    }

    public static Optional<String> getOptional(String key) {
        return Optional.ofNullable(get(key));
    }

    public static String getOrDefault(String key, String defaultValue) {
        String value = get(key);
        return value != null ? value : defaultValue;
    }

    public static void clear() {
        CONTEXT.remove();
    }

    public static Optional<String> appKey() {
        return getOptional(APP_KEY_HEADER_KEY);
    }

    public static Optional<String> sign() {
        return getOptional(SIGN_HEADER_KEY);
    }

    public static Optional<String> timestamp() {
        return getOptional(TIMESTAMP_HEADER_KEY);
    }

}
